import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from "@/views/Home";
import Login from "@/views/Login";
import index from "@/views/Index";
import UserCenter from "@/views/UserCenter";
import store from "../store"
import axios from "axios";

Vue.use(VueRouter)

const routes = [
  {
    path: '/home',
    name:'Home',
    component : Home,
    children:[
      {
        path: '/index',
        name: 'Index',
        component: index
      },
      {
        path: '/userCenter',
        name: 'UserCenter',
        component:UserCenter
      }
    ]
  },
  {
    path:'/',
    redirect: '/login'
  },
  {
    path:'/login',
    name: 'Login',
    component:Login
  },

]

const router = new VueRouter({
  mode:'history',
  base:process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  //路由的状态（ture、false）
  let hasRouter=store.state.menus.hasRouter;
  //先判断有没有添加过路由，如果没有才继续请求
  if (!hasRouter){
    axios.get("http://127.0.0.1:8081/sys/menu/nav",{
      headers:{
        Authorization:localStorage.getItem("token")
      }
    }).then(result=>{
      console.log(result.data.data.nav);
      //  拿到menuList
      store.commit("setMenuList",result.data.data.nav);
      //  拿到用户权限
      store.commit("setPermList",result.data.data.authorities);
      //  动态绑定路由
      let newRouters=router.options.routes;
      //变量数据模型
      result.data.data.nav.forEach(item=>{
        //如果数据模型有children，在遍历它的children
        if (item.children){
          item.children.forEach(e=>{
            //menuToRouter是把数据模型中的json数据转换成路由
            let route=menuToRouter(e);
            if (route){
              newRouters[0].children.push(route)
            }
          })
        }
      })
      router.addRoutes(newRouters);
      hasRouter=true;
      store.commit("changeRouteStatus",hasRouter)
    })
  }
  next()
})
//导航转成路由
const menuToRouter=(menu)=>{
  if (!menu.component){
    return null;
  }
  let route={
    name:menu.name,
    path:menu.path,
    component:'',
    meta:{
      icon:menu.icon,
      title:menu.title
    }
  }
  route.component= ()=>import('@/views/'+menu.component+'.vue')
  return  route;
}
export default router
